
using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.UserRoles.Commands;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.UserRoles.CommandHandlers;

public class RemoveUserFromRoleCommandHandler : IRequestHandler<RemoveUserFromRoleCommand, Result>
{
    private readonly IUserService _userService;
    private readonly IRoleService _roleService;
    private readonly IUserRoleService _userRoleService;

    public RemoveUserFromRoleCommandHandler(IUserRoleService userRoleService, IUserService userService, IRoleService roleService)
    {
        _userRoleService = userRoleService;
        _roleService = roleService;
        _userService = userService;

    }
    public async Task<Result> Handle(RemoveUserFromRoleCommand request, CancellationToken cancellationToken)
    {

        var userData = await _userService.GetUserByIdAsync(request.UserId);
        var roleData = await _roleService.GetRoleByIdAsync(request.RoleId);

        var user = UserAggregate.LoadFromPersistence(userData!.Id, userData.UserName, userData.Email, userData.Roles.ToList());
        var role = Role.LoadFromPersistence(roleData!.Id,roleData.Code, roleData.Name,roleData.PermissionIds,roleData.Description,roleData.Status);
        
        user.RemoveRole(role.Name);

        var result = await _userRoleService.RemoveRoleAsync(request.UserId, request.RoleId);
        if (!result.Succeeded) return Result.Failure(result.Error ?? "删除角色失败");

        return Result.Success();
    }
}